package com.wg.msshopsp.backendmanagement.shop.mapper;

import com.wg.msshopsp.backendmanagement.shop.entity.Product;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;

import java.util.List;

@Mapper
public interface ProductMapper  {
    // 插入商品，并获取自增的商品ID
    @Insert("INSERT INTO product (" +
            "shop_id, name, price_before, price_after, " +
            "type, count, create_time, status" +  // 补充status字段
            ") VALUES (" +
            "#{shopId}, #{name}, #{priceBefore}, #{priceAfter}, " +
            "#{type}, #{count}, NOW(), #{status}" +  // 补充status的值
            ")")
    // 插入后获取自增ID，赋值给Product对象的id字段
    @SelectKey(
            statement = "SELECT LAST_INSERT_ID()", // MySQL获取最新自增ID的函数
            keyProperty = "id", // 把获取到的ID赋值给Product的id属性
            resultType = Long.class, // ID的类型是Long
            before = false, // false表示先执行插入，再执行这个查询（正确顺序）
            statementType = StatementType.STATEMENT
    )
    void insert(Product product); // 参数是Product对象，MyBatis会自动取其中的字段值



    @Select("SELECT id AS product_id, shop_id, name AS product_name, main_img, name, status, " +
            "create_time, price_before, price_after, count, type, buy_ed " +
            "FROM product WHERE shop_id = #{shopId}")
    @Results({
            @Result(id = true, property = "id", column = "product_id"), // 商品ID（唯一标识）
            @Result(property = "shopId", column = "shop_id"),
            @Result(property = "name", column = "product_name"),
            @Result(property = "mainImg", column = "main_img"),
            @Result(property = "name", column = "name"),
            @Result(property = "status", column = "status"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "priceBefore", column = "price_before"),
            @Result(property = "priceAfter", column = "price_after"),
            @Result(property = "count", column = "count"),
            @Result(property = "type", column = "type"),
            @Result(property = "buyEd", column = "buy_ed"),
            // 关联查询商品的规格（一对多）
            @Result(
                    property = "specs", // 对应 Product 中的 specs 属性
                    column = "product_id", // 传递商品ID给规格查询
                    many = @Many(select = "com.wg.msshopsp.backendmanagement.shop.mapper.ProductSpecMapper.getSpecsByProductId")
            )
    })
    List<Product> getProductsByShopId(@Param("shopId") Integer shopId);


    // 新增：根据ID查询商品（用于校验存在性）
    @Select("SELECT id FROM product WHERE id = #{id}")
    Product selectById(@Param("id") Long id);

    // 新增：更新商品基本信息
    @Update("UPDATE product SET " +
            "name = #{name}, " +
            "price_before = #{priceBefore}, " +
            "price_after = #{priceAfter}, " +
            "count = #{count}, " +
            "buy_ed = #{buyEd}, " +
            "status = #{status}, " +
            "type = #{type} " +
            "WHERE id = #{id}")
    void update(Product product);

}